package com.youlin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.youlin.dto.BaseDataResDto;
import com.youlin.dto.Status;
import com.youlin.dto.req.FindAllAreaReqDto;
import com.youlin.entities.BygAppInfo;
import com.youlin.entities.BygArea;
import com.youlin.mapper.BygAreaMapper;
import com.youlin.service.BygAppInfoService;
import com.youlin.service.BygAreaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class BygAreaServiceImpl extends ServiceImpl<BygAreaMapper, BygArea> implements BygAreaService {

    @Autowired
    private BygAppInfoService bygAppInfoService;

    @Override
    public BaseDataResDto<List<BygArea>> findAllAreas(FindAllAreaReqDto data) {
        Integer parentId = data.getParentId();

        List<Integer> areaIds = null;
        if (data.getQuery()) { // 查询所有已关联单位的省份或城市
            LambdaQueryWrapper<BygAppInfo> select = Wrappers.lambdaQuery(BygAppInfo.class)
                    .select(BygAppInfo::getProvince, BygAppInfo::getCity);
            List<BygAppInfo> appInfos = bygAppInfoService.list(select);
            if (parentId == 1) areaIds = appInfos.parallelStream()
                    .map(BygAppInfo::getProvince).distinct().collect(Collectors.toList());
            else areaIds = appInfos.parallelStream()
                    .map(BygAppInfo::getCity).distinct().collect(Collectors.toList());
        }

        List<BygArea> bygAreas;
        if (parentId == 2) { // 查询所有城市
            LambdaQueryWrapper<BygArea> provinceWrapper = Wrappers.lambdaQuery(BygArea.class).eq(BygArea::getParentId, 1);
            List<Integer> provinceIds = list(provinceWrapper).parallelStream().map(BygArea::getAreaId).collect(Collectors.toList());
            LambdaQueryWrapper<BygArea> cityWrapper = Wrappers.lambdaQuery(BygArea.class).in(BygArea::getParentId, provinceIds);
            if (CollectionUtils.isNotEmpty(areaIds)) cityWrapper.in(BygArea::getAreaId, areaIds);
            bygAreas = list(cityWrapper);
        } else { // 根据 parentId 查询所有省份或城市
            LambdaQueryWrapper<BygArea> wrapper = Wrappers.lambdaQuery(BygArea.class).eq(BygArea::getParentId, parentId);
            if (CollectionUtils.isNotEmpty(areaIds)) wrapper.in(BygArea::getAreaId, areaIds);
            bygAreas = list(wrapper);
        }

        return new BaseDataResDto<List<BygArea>>(Status.SUCCESS).setData(bygAreas);
    }

}
